//
//  listTableViewController.m
//  CoreData2
//
//  Created by ibokan on 14-11-5.
//  Copyright (c) 2014年 ibokan. All rights reserved.
//

#import "listTableViewController.h"
#import "AppDelegate.h"
#import "Student.h"
@interface listTableViewController ()
@property(strong,nonatomic)NSFetchedResultsController *fetchedResultsController;
@property(strong,nonatomic)NSFetchedResultsController *searchController;  //保存查询结果用
@property(strong,nonatomic)NSManagedObjectContext *managedObjectContext;
@end

@implementation listTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    self.managedObjectContext = delegate.managedObjectContext;
    
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
    
    //排序描述
    NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"stdNo" ascending:YES];
    NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"classmate" ascending:YES];
    
    [request setSortDescriptors:@[sort2,sort1]];
    
    //分组的属性，必须出现在排序属性列表中，并且出现在第一位，用来分组
    self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"classmate" cacheName:@"r1"];
    
    
    //上下文变化后调用委托中的方法来更新tableview
    self.fetchedResultsController.delegate = self;
    
    
    [self.fetchedResultsController performFetch:nil];   //执行语句
    
    
    //增加search bar and search display controller  之后进行注册
    [self.searchDisplayController.searchResultsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"searchCell"];
    
    
    //设置显示查询结果的 数据源，委托代理
    self.searchDisplayController.searchResultsDataSource = self;
    self.searchDisplayController.searchResultsDelegate = self;
    
    
    
    self.searchDisplayController.delegate = self;
    
    
    
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //判断是哪个tableview，是自身的，还是搜索界面
    if (tableView == self.tableView) {
        return self.fetchedResultsController.sections.count;
    }else{
        return self.searchController.sections.count;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        id <NSFetchedResultsSectionInfo> sectionInfo = self.fetchedResultsController.sections[section];
        return [sectionInfo numberOfObjects];
    }else{
        id <NSFetchedResultsSectionInfo> sectionInfo = self.searchController.sections[section];
        return [sectionInfo numberOfObjects];
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        
        UILabel *stdNoLabel = (UILabel*)[cell.contentView viewWithTag:1];
        UILabel *stdNameLabel = (UILabel*)[cell.contentView viewWithTag:2];
        UILabel *classmateLabel = (UILabel*)[cell.contentView viewWithTag:3];
        
        Student *std = [self.fetchedResultsController objectAtIndexPath:indexPath];
        stdNoLabel.text = std.stdNo;
        stdNameLabel.text = std.stdName;
        classmateLabel.text = std.classmate;
        return cell;
        
    }else{
        
        //标示符为注册时的标示符
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell" forIndexPath:indexPath];
    
       Student *std = [self.searchController objectAtIndexPath:indexPath];
        cell.textLabel.text = std.stdName;
        return  cell;
    }
}


-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        id <NSFetchedResultsSectionInfo> sectionInfo = self.fetchedResultsController.sections[section];
        return [sectionInfo name];
    }else{
        id <NSFetchedResultsSectionInfo> sectionInfo = self.searchController.sections[section];
        return [sectionInfo name];
    }
    
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}


- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
    
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
                          withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex]
                          withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
    
    UITableView *tableView = self.tableView;
    
    switch(type) {
            
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeUpdate:
            [tableView reloadRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView endUpdates];
}


//当search bar中发生改变后，会调用这个方法
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
    
    //指定查询条件

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stdName BEGINSWITH %@",searchString];
    
    [request setPredicate:predicate];
    
    
    //排序描述
    NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"stdNo" ascending:YES];
    NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"classmate" ascending:YES];
    
    [request setSortDescriptors:@[sort2,sort1]];
    
    
    
    
    self.searchController = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"classmate" cacheName:nil];
    [self.searchController performFetch:nil];
    
    
    return YES;
}












@end
